local lantern_list = {"lantern", "myth_redlantern", "pumpkin_lantern", "redlantern", "miniboatlantern", "bottlelantern"}
local fireSource_list = {"dragonflyfurnace", "stafflight", "staffcoldlight","moonbase"}
local heat_list = {"heatrock", "icire_rock"}
local precedence = {"birdtrap"}
local rabbit_list = {"rabbithole"}
local trap_list = {"trap"}
local fireSource_range = 4

local function getThing(all_items, list)
    for _,item in pairs(all_items)do
        if item.prefab and table.contains(list, item.prefab) then
            return item
        end
    end
end

local function getFire(all_items)
    local pos = GLOBAL.ThePlayer:GetPosition()
    if GLOBAL.FindEntity(GLOBAL.ThePlayer, fireSource_range, function(inst) return table.contains(fireSource_list, inst.prefab) end) -- 附近有指定热源
    or (pos and (not IsEmpty(GLOBAL.TheSim:FindEntities(pos.x, 0, pos.z, fireSource_range, {"plant", "fire"}, {"INLIMBO", "FX"}))    -- 附近有燃烧的植物（排除拿火把打生物）
    or not IsEmpty(GLOBAL.TheSim:FindEntities(pos.x, 0, pos.z, fireSource_range, {"campfire", "fire"}, {"INLIMBO", "FX"}))))         -- 附近有燃烧的营火
    then
        return getThing(all_items, heat_list)
    end
end

local function getTrap(all_items)
    if GLOBAL.FindEntity(GLOBAL.ThePlayer, fireSource_range, function(inst) return table.contains(rabbit_list, inst.prefab) end) then
        return getThing(all_items, trap_list)
    end
end

local function Drop()
    -- if not _G.ThePlayer then return end
    if InGame() then
        local items = GetItemsFromAll()
        local drop_sth = getThing(items, precedence)        -- 优先丢弃
            or getFire(items)                               -- 丢暖石
            or getTrap(items)                               -- 丢陷阱
            or getThing(items, lantern_list)                -- 丢提灯
        if drop_sth then
            GLOBAL.ThePlayer.replica.inventory:DropItemFromInvTile(drop_sth)
        end
    end
end

GLOBAL.TheInput:AddKeyDownHandler(GetModConfigData("sw_lantern"), Drop)
